#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
from google.appengine.ext import db
from apptwitter import AppEngineTwitter
from dservice import DService
from delladb import Delladb
from django.utils import simplejson

class TwiService:
    """Class to processing information from the twitter users"""  
    def __init__( self ):
        """initializing the username and password"""
        self._oauth_key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxx' # oauth_key
        self._oauth_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxx' # oauth_secret
        self._actoken='xxxxxxxxxxxxxxxxxxxxxxxxxxx' # della actoken
        self._actokense='xxxxxxxxxxxxxxxxxxxxxxxxxxx' # della actoken_se
        self._tww=AppEngineTwitter()
        self._tww.set_oauth(self._oauth_key,
                            self._oauth_secret,
                            self._actoken,
                            self._actokense)


    def checkQueries(self):
        results=self.getMessage()
        for content in results:
            match=self.praseMsg(content)
            if(match<>[]):
                dservice=DService(match[0])
                respons=dservice.parseCommand()
                if(respons<>[] and respons[0]<>'pass'):
                    for re in respons:
                        re='@'+content['user']['screen_name'].encode('utf-8')+' '+re
                        self.sentMessage(re)
        if(results<>[]):
            self.updateTwiMsgId(results[0]['id'])

        results=self.getDM()
        for content in results:
            print content['text'].encode('utf-8')
            dservice=DService(content['text'])
            respons=dservice.parseCommand()
            print str(len(respons))
            if(respons<>[] and respons[0]<>'pass'):
                for re in respons:
                    self.sentDM(content['sender']['screen_name'],re)
        if(results<>[]):
            self.updateTwiDMId(results[0]['id'])
            
             
    def praseMsg(self,content):
        regex=r'^@idella001 (.*)'
        return re.findall(regex,content['text'].lower())

    
    def getMessage(self):
        since_id=self.getTwiMsgId()
        retry=3
        statuscode=500
        for tim in range(retry):
            try:
                statuscode=self._tww.mentions(since_id)
                if(statuscode==200):
                    break
            except:
                pass
        if(statuscode<>200):
            return []
        else:
            contents = simplejson.loads(self._tww.getContent())
            return contents

            
    def sentMessage(self,msg):
        retry=4
        statuscode=500
        for tim in range(retry):
            try:
                statuscode=self._tww.update(msg)
                if(statuscode==200):
                    break
            except:
                pass           



    def getDM(self):
        since_id=self.getTwiDMId()
        retry=3
        statuscode=500
        for tim in range(retry):
            try:
                statuscode=self._tww.getDMessage(since_id)
                if(statuscode==200):
                    break
            except:
                pass
        if(statuscode<>200):
            return []
        else:
            contents = simplejson.loads(self._tww.getContent())
            return contents


    def sentDM(self,user,msg):
        retry=4
        statuscode=500
        for tim in range(retry):
            try:
                statuscode=self._tww.sentDMessage(user,msg)
                print '=status=:'+str(statuscode)
                if(statuscode==200):
                    break
            except:
                pass

          
    def getTwiMsgId(self):
        q=db.GqlQuery("SELECT * FROM Delladb")
        if(q.count()):
            return q[0].twimsg
        else:
            return 9547292125


    def updateTwiMsgId(self,msgid):
        q=db.GqlQuery("SELECT * FROM Delladb")
        for enty in q:
            enty.twimsg=msgid
            db.put(enty)
        

    def getTwiDMId(self):
        q=db.GqlQuery("SELECT * FROM Delladb")
        if(q.count()):
            return q[0].twidm
        else:
            return 862969080


    def updateTwiDMId(self,msgid):
        q=db.GqlQuery("SELECT * FROM Delladb")
        for enty in q:
            enty.twidm=msgid
            db.put(enty)        




        
            
        
